package com.hww.mq.producer;

import com.hww.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

/**
 * @Author: youdao.hww
 * @Date: 5/16/24
 * @Desc: 默认情况下生产者会把消息以Round Robin轮询方式发送到不同的Queue分区队列；而消费消息时会从
 * 多个Queue上拉取消息，这种情况下的发送和消费是不能保证顺序的。如果将消息仅发送到同一个
 * Queue中，消费时也只从这个Queue上拉取消息，就严格保证了消息的顺序性。
 */
@Slf4j
@Service
public class MQProducerOrderService {


    @Autowired
    private RocketMQTemplate rocketMQTemplate;



    /*发送同步顺序消息*/
    public SendResult syncSendOrderly(String topic, User user) {
        SendResult sendResult = rocketMQTemplate.syncSendOrderly(topic, MessageBuilder.withPayload(user).build(), String.valueOf(user.getId()), 3000);
        if (sendResult.getSendStatus() == SendStatus.SEND_OK) {
            log.info("顺序消息发送成功");
        } else {
            log.error("顺序消息发送失败");
        }
        return sendResult;
    }


    /*发送同步顺序消息*/
    public void asyncSendOrderly(String topic, User user) {
        rocketMQTemplate.asyncSendOrderly(topic, MessageBuilder.withPayload(user).build(), String.valueOf(user.getId()), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("asyncSendOrderly-异步顺序消息发送成功");
            }

            @Override
            public void onException(Throwable throwable) {
                log.info("asyncSendOrderly-异步顺序消息发送失败");

            }
        });

    }


}
